<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>

<h1>表单事件</h1>
<hr>


<div>
    <form id="loginForm" action="loginok.html" method="get">
        用户名：<input type="text" id="username" value="">
        籍贯: <select id="province" value=""></select> <select id="city" value=""></select>
        <input type="submit" value="登录"/>
    </form>
</div>

<script>
    let provinces = ['河北','河南','山东','山西'];
    let citys =[
        ['石家庄','保定','沧州','唐山','邯郸'],
        ['郑州','洛阳','开封','南阳','驻马店'],
        ['济南','青岛','泰安','烟台','日照'],
        ['太原','大同','晋中','运城','临汾'],
    ];
    let currentProvinceIndex = 0;
    //初始化省份列表
    function initProvinceList(){
        provinces.forEach(function(v,i){
            let provinceHTML ="";
            if(i==0){
                provinceHTML = '<option selected>'+v+'</option>'
            }else{
                provinceHTML = '<option>'+v+'</option>'
            }
            $("#province").append(provinceHTML);
        });
    }
    //初始化城市列表
    function initCityList(index){
        $("#city").empty();
        citys[currentProvinceIndex].forEach(function(v,i){
            let cityHTML ="";
            if(i==0){
                cityHTML = '<option selected>'+v+'</option>'
            }else{
                cityHTML = '<option>'+v+'</option>'
            }
            $("#city").append(cityHTML);
        });
    }

    $(function(){

        initProvinceList();
        initCityList(currentProvinceIndex);

        $("#province").change(function(){
            currentProvinceIndex = $("#province").get(0).selectedIndex;
            //更新城市列表
            initCityList(currentProvinceIndex);
        })
        $("#loginForm").submit(function(){
            console.log('执行登录...');
            if($("#username").val().length<=0) {
                alert('用户名不能为空！');
                return false; //返回 false 则不执行表单提交。
            }
            let username = $("#username").val();
            let provice = $("#province").val();
            let city = $("#city").val();
            alert("登录成功，用户名："+username+" 籍贯："+provice+","+city);
            return true;
        })
    })
</script>
</body>
</html>
